package com.atguigu.springcloud.myloadbalancer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalancerImpl implements MyLoadBalancer {

    //创建原子整型
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    //利用CAS + 自旋锁进行原子整数的自增
    private int getAndIncrement(){
         int now ;
         int next ;
         do{
             now = atomicInteger.get();
             next = now > Integer.MAX_VALUE ? 0: now+1 ;
         }while (!atomicInteger.compareAndSet(now,next));
        System.out.println("当前循环总次数: "+ next);
         return next;

    }
    //自旋锁增加

    @Override
    public ServiceInstance getInstance(List<ServiceInstance> list) {
        int size = list.size();
        //轮询算法进行服务选择
        int returnSize = this.getAndIncrement() % size;
        return list.get(returnSize);
    }
}
